#if UNITY_WEBGL && !UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace ET.WebJS
{
    public class WServiceJS: AService
    {
        private long idGenerater = 200000000;
        
        private WebSocket webSocket;
        
        private readonly Dictionary<long, WChannelJS> channels = new Dictionary<long, WChannelJS>();
        
        public WServiceJS(ThreadSynchronizationContext threadSynchronizationContext)
        {
            this.ThreadSynchronizationContext = threadSynchronizationContext;
        }
        
        private long GetId
        {
            get
            {
                return ++this.idGenerater;
            }
        }
        
        public WChannelJS Create(string address, long id)
        {
			this.webSocket = new WebSocket(address);
            WChannelJS channel = new WChannelJS(id, webSocket, this);
            this.channels[channel.Id] = channel;
            return channel;
        }

        public override void Remove(long id)
        {
            WChannelJS channel;
            if (!this.channels.TryGetValue(id, out channel))
            {
                return;
            }

            this.channels.Remove(id);
            channel.Dispose();
        }

        public override bool IsDispose()
        {
            return this.ThreadSynchronizationContext == null;
        }

        protected override void Get(long id, string address)
        {
            if (!this.channels.TryGetValue(id, out _))
            {
                this.Create(address, id);
            }
        }

        public override void Dispose()
        {
            this.ThreadSynchronizationContext = null;
            this.webSocket?.CloseAsync();
            this.webSocket = null;
        }       
        
        protected override void Get(long id, IPEndPoint address)
        {
            
        }

        protected override void Send(long channelId, long actorId, MemoryStream stream)
        {
            this.channels.TryGetValue(channelId, out WChannelJS channel);
            if (channel == null)
            {
                return;
            }
            channel.Send(stream);
        }

        public override void Update()
        {
            
        }

    }
}
#endif